#include "downloadhistory.h"
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QStandardPaths>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonArray>
#include <QtCore/QJsonObject>
#include <QtCore/QDebug>

DownloadHistory::DownloadHistory(QObject *parent)
    : QObject(parent)
{
    loadHistory();
}

DownloadHistory::~DownloadHistory()
{
    saveHistory();
}

void DownloadHistory::addRecord(const DownloadRecord &record)
{
    m_records.append(record);
}

const QList<DownloadRecord>& DownloadHistory::getRecords() const
{
    return m_records;
}

QList<DownloadRecord> DownloadHistory::getRecordsByCategory(const QString &category) const
{
    QList<DownloadRecord> result;
    for (const auto &record : qAsConst(m_records)) {
        if (record.category == category) {
            result.append(record);
        }
    }
    return result;
}

QList<DownloadRecord> DownloadHistory::getRecordsByTag(const QString &tag) const
{
    QList<DownloadRecord> result;
    for (const auto &record : qAsConst(m_records)) {
        if (record.tags.contains(tag)) {
            result.append(record);
        }
    }
    return result;
}

QList<DownloadRecord> DownloadHistory::searchRecords(const QString &keyword) const
{
    QList<DownloadRecord> result;
    for (const auto &record : qAsConst(m_records)) {
        if (record.fileName.contains(keyword, Qt::CaseInsensitive) || 
            record.url.contains(keyword, Qt::CaseInsensitive)) {
            result.append(record);
        }
    }
    return result;
}

void DownloadHistory::removeRecord(int index)
{
    if (index >= 0 && index < m_records.size()) {
        m_records.removeAt(index);
    }
}

void DownloadHistory::clearHistory()
{
    m_records.clear();
}

void DownloadHistory::saveHistory()
{
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(dataPath);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    
    QString filePath = dir.filePath("download_history.json");
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug() << "Cannot open file for writing:" << filePath;
        return;
    }
    
    QJsonArray recordsArray;
    for (const auto &record : qAsConst(m_records)) {
        QJsonObject recordObject;
        recordObject["url"] = record.url;
        recordObject["fileName"] = record.fileName;
        recordObject["filePath"] = record.filePath;
        recordObject["fileSize"] = static_cast<qint64>(record.fileSize);
        recordObject["startTime"] = record.startTime.toString(Qt::ISODate);
        recordObject["endTime"] = record.endTime.toString(Qt::ISODate);
        recordObject["completed"] = record.completed;
        recordObject["category"] = record.category;
        
        QJsonArray tagsArray;
        for (const QString &tag : record.tags) {
            tagsArray.append(tag);
        }
        recordObject["tags"] = tagsArray;
        
        recordsArray.append(recordObject);
    }
    
    QJsonDocument doc(recordsArray);
    file.write(doc.toJson());
    file.close();
}

void DownloadHistory::loadHistory()
{
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QString filePath = QDir(dataPath).filePath("download_history.json");
    
    QFile file(filePath);
    if (!file.exists() || !file.open(QIODevice::ReadOnly)) {
        return;
    }
    
    QByteArray data = file.readAll();
    file.close();
    
    QJsonParseError error;
    QJsonDocument doc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        qDebug() << "Error parsing JSON:" << error.errorString();
        return;
    }
    
    if (!doc.isArray()) {
        return;
    }
    
    QJsonArray recordsArray = doc.array();
    m_records.clear();
    
    for (const auto &recordValue : recordsArray) {
        if (!recordValue.isObject()) {
            continue;
        }
        
        QJsonObject recordObject = recordValue.toObject();
        DownloadRecord record;
        record.url = recordObject["url"].toString();
        record.fileName = recordObject["fileName"].toString();
        record.filePath = recordObject["filePath"].toString();
        record.fileSize = recordObject["fileSize"].toVariant().toLongLong();
        record.startTime = QDateTime::fromString(recordObject["startTime"].toString(), Qt::ISODate);
        record.endTime = QDateTime::fromString(recordObject["endTime"].toString(), Qt::ISODate);
        record.completed = recordObject["completed"].toBool();
        record.category = recordObject["category"].toString();
        
        QJsonArray tagsArray = recordObject["tags"].toArray();
        for (const auto &tagValue : tagsArray) {
            record.tags.append(tagValue.toString());
        }
        
        m_records.append(record);
    }
}